//
//  SEGPGCDetailViewModel.m
//  SEGWebView-SEGWebView
//
//  Created by Clavis on 2020/6/11.
//

#import "SEGPGCDetailViewModel.h"
#import "SEGPGCDeteailManager.h"
#import "SEGPictorialManager.h"
#import <SEGPlatform/SEGCommunitySocialManager.h>

@interface SEGPGCDetailViewModel ()

@property (nonatomic, strong) SEGPGCDeteailManager *pgcDeteailManager;
@property (nonatomic, strong) SEGCommunitySocialManager *socialManager;
@property (nonatomic, strong) SEGPictorialManager *pictorialManager;

// 数据处理
@property (nonatomic, assign) __block NSInteger commentPageIndex;
/// 喜欢列表数据
@property (nonatomic, strong, readwrite) SEGPGCFixViewModel *fixModel;
/// 普通评论总数
@property (nonatomic, assign, readwrite) NSInteger totalComment;
/// 频道列表下标
@property (nonatomic, assign) NSInteger channelPageIndex;

@end

@implementation SEGPGCDetailViewModel
#pragma mark - PGC数据处理
/// 请求PGC详情
- (RACSignal *)requestDetailSignal {
    if (!_requestDetailSignal) {
        @weakify(self);
        _requestDetailSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            // 请求PGC详情
            [self.pgcDeteailManager requestPgcDetailWithPictorialId:ValueToString(self.pgcID) finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (!isSuccessed) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                    return ;
                }
                
                // 发送信号 VC接收&刷新页面
                [subscriber sendNext:self.pgcDeteailManager.pgcDetailModel];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }
    return _requestDetailSignal;
}


/// 请求点赞列表
- (RACSignal *)requestLikeListSignal {
    if (!_requestLikeListSignal) {
        @weakify(self);
        _requestLikeListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.pgcDeteailManager requestPGCLikeListWithObjId:self.pgcID objType:self.objType finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    self.fixModel = result;
                    [subscriber sendNext:self.pgcDeteailManager.pgcDetailModel];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _requestLikeListSignal;
}

/// PGC收藏
- (RACCommand *)pgcLikeCommand {
    if (!_pgcLikeCommand) {
        @weakify(self);
        _pgcLikeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                BOOL currentLikeStatus = [input boolValue];
                if (currentLikeStatus) { // 取消点赞
                    [self.pgcDeteailManager requestCancelPraiseByobjId:self.pgcID objType:self.objType Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                        if (isSuccessed) {
                            [subscriber sendNext:input];
                            [subscriber sendCompleted];
                        } else {
                            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                            [subscriber sendError:error];
                        }
                    }];
                } else { // 点赞
                    [self.pgcDeteailManager requestPraiseAttentByObjId:self.pgcID ObjType:self.objType Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                        if (isSuccessed) {
                            [subscriber sendNext:input];
                            [subscriber sendCompleted];
                        } else {
                            NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                            [subscriber sendError:error];
                        }
                    }];
                }
                return nil;
            }];
        }];
    }
    return _pgcLikeCommand;
}

#pragma mark - PGC评论处理
/// 请求评论列表
- (RACSignal *)requestCommentListSignal {
    if (!_requestCommentListSignal) {
        @weakify(self);
        _requestCommentListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            
            [self.pgcDeteailManager requestCommentListWithObjId:self.pgcID objType:self.objType pageNo:self.commentPageIndex+1 finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    self.commentPageIndex += 1;
                    self.totalComment = self.pgcDeteailManager.totalComment;
                    [subscriber sendNext:[self.pgcDeteailManager.commentsArray copy]];
                    [subscriber sendCompleted];
                } else {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:codeType.integerValue userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                }
            }];
            
            return nil;
        }];
    }
    return _requestCommentListSignal;
}

/// 请求热门评论信号量
- (RACSignal *)requestHotCommentListSignal {
    if (!_requestHotCommentListSignal) {
        _requestHotCommentListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            [self.pgcDeteailManager requestHotCommentWithObjId:self.pgcID objType:self.objType finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed) {
                    [subscriber sendNext:result];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _requestHotCommentListSignal;
}

/// 请求发送评论
- (RACCommand *)sendCommentCommand {
    if (!_sendCommentCommand) {
        @weakify(self);
        _sendCommentCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                RACTupleUnpack(NSString *selectedIndexPath, NSNumber *selectChildNumber, SEGSharedCommentModel *selectedCommentModel, NSString *content) = input;
                NSInteger selectChildIndex = [selectChildNumber integerValue];
                
                // 异常判断
                if (content.length < 2) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:@"输入内容不能少于2个字。"}];
                    [subscriber sendError:error];
                    return nil;
                }
                
                if (content.length > 140) {
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:@{NSLocalizedDescriptionKey:@"亲，您输入的内容已超过140字。"}];
                    [subscriber sendError:error];
                    return nil;
                }
                
                // 处理数据
                NSString *objTitleForMsg = @"";
                NSString *byReviewNick = @"";
                NSString *byReviewId = @"";
                NSString *byReviewUserId = @"";
                NSString *sourceCommentId = @"";
                if (selectedIndexPath) {//对评论的回复
                    byReviewId = selectedCommentModel.comment.id;
                    byReviewNick = selectedCommentModel.user.nickName;
                    byReviewUserId = selectedCommentModel.user.userId;
                    objTitleForMsg = selectedCommentModel.comment.content;
                    sourceCommentId = byReviewId;
                    if (selectChildIndex != -1) {
                        SEGSharedCommentChildCommentModel *childModel = selectedCommentModel.comment.childComment[selectChildIndex];
                        byReviewId = childModel.comment.id;
                        byReviewNick = childModel.user.nickName;
                        byReviewUserId = childModel.user.userId;
                        objTitleForMsg = childModel.comment.content;
                    }
                } else {//对文章的评论
                    objTitleForMsg = self.pgcDeteailManager.pgcDetailModel.pictorialTitle;
                }
                
                //当昵称为空时传入手机号码
                NSString* nickName = kAccountNickName.length ? kAccountNickName : kAccountMobile;
                NSString* communityName = [NSString stringWithFormat:@"来自%@ %@", kAccountCityName, kAccountCommunityName];
                
                // 请求接口
                [self.pictorialManager requestpictoriaCommentSaveByobjId:self.pgcID
                                                                 objType:@"1"
                                                          commentContent:content
                                                                  userId:kAccountUserID
                                                                 creator:nickName ?: @""
                                                              byReviewId:byReviewId ?: @""
                                                         sourceCommentId:sourceCommentId ?: @""
                                                            byReviewNick:byReviewNick ?: @""
                                                          byReviewUserId:byReviewUserId ?: @""
                                                           communityName:communityName ?: @""
                                                             communityId:kAccountCommunityID
                                                           objSendUserId:kAccountUserID
                                                         objPicUrlForMsg:@""
                                                          objTitleForMsg:objTitleForMsg ?: @""
                                                             parentObjId:self.pgcID
                                                               pramsType:1001
                                                           parentObjType:SEGUserType_PICTORIAL
                                                                Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        [subscriber sendNext:@""];
                        
                        if (!selectedIndexPath) { // 对PGC文章评论
                            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.pgc module:SEGIntegralModule.articleDetail businessID:self.pgcID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                            }];
                            //刷新评论列表
                            self.commentPageIndex = 0;
                            [self.requestCommentListSignal subscribeNext:^(id  _Nullable x) {
                                if (self.updateDataSubject) {
                                    [self.updateDataSubject sendNext:RACTuplePack(@(SEGPGCCellDisplayType_Comment), x, nil)];
                                }
                            }];
                            
                            // 加载热门评论
                            [self.requestHotCommentListSignal subscribeNext:^(id  _Nullable x) {
                                if (self.updateDataSubject) {
                                    [self.updateDataSubject sendNext:RACTuplePack(@(SEGPGCCellDisplayType_HotComment), x, nil)];
                                }
                            }];
                            [subscriber sendCompleted];
                            return;
                        }
                        
                        // 对评论进行回复
                        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.reply module:SEGIntegralModule.articleDetail businessID:self.pgcID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                        }];
                        // 请求子评论列表数据
                        [self.pgcDeteailManager requestChildCommentsWithObjId:self.pgcID objType:self.objType sourceCommentId:sourceCommentId finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                            if (isSuccessed) {
                                //替换子评论 刷新界面
                                NSDictionary *data = [result valueForKey:@"data"];
                                NSArray *childComments = [data valueForKey:@"childComments"];
                                NSArray<SEGSharedCommentChildCommentModel *> *childCommentArray = [childComments.rac_sequence map:^id _Nullable(id  _Nullable value) {
                                    if ([value isKindOfClass:[NSDictionary class]]) {
                                        return [SEGSharedCommentChildCommentModel yy_modelWithDictionary:value];
                                    }
                                    return nil;
                                }].array;
                                selectedCommentModel.comment.childComment = childCommentArray;
                                if (self.updateDataSubject) {
                                    [self.updateDataSubject sendNext:RACTuplePack(@(SEGPGCCellDisplayType_Comment), selectedCommentModel, selectedIndexPath)];
                                }
                            }
                        }];
                        [subscriber sendCompleted];
                    }
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                }];
                return nil;
            }];
        }];
    }
    return _sendCommentCommand;
}


/// 删除评论
- (RACCommand *)deleteCommetCommand {
    if (!_deleteCommetCommand) {
        @weakify(self);
        _deleteCommetCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                RACTupleUnpack(SEGSharedCommentModel *selectCommentModel, NSNumber *isHotCommentNumber, NSNumber *deleteIndexNumber, NSNumber *selectChildIndexNumber) = input;
                NSInteger selectChildIndex = [selectChildIndexNumber integerValue];
                NSInteger deleteIndex = [deleteIndexNumber integerValue];
                BOOL isHotComment = [isHotCommentNumber boolValue];
                NSString *commentID = selectChildIndex == -1 ? selectCommentModel.comment.id : selectCommentModel.comment.childComment[selectChildIndex].comment.id;
                NSString *objType = selectCommentModel.comment.objType;
                
                [self.pgcDeteailManager requestDeleteCommentWithCommentId:commentID?:@"" objType:objType?:@"" finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        if (selectChildIndex == -1) { // 删除评论
                            if (isHotComment) { // 热门评论
                                NSMutableArray *tempCommentArray = [self.pgcDeteailManager.hotCommentArray mutableCopy];
                                if (tempCommentArray.count > deleteIndex) {
                                    [tempCommentArray removeObjectAtIndex:deleteIndex];
                                    NSLog(@"💎💎💎💎1  删除热门评论 HotComment.count=%ld", tempCommentArray.count);
                                }
                                self.pgcDeteailManager.hotCommentArray = [tempCommentArray copy];
                            } else { // 普通评论
                                NSMutableArray *tempCommentArray = [self.pgcDeteailManager.commentsArray mutableCopy];
                                if (tempCommentArray.count > deleteIndex) {
                                    [tempCommentArray removeObjectAtIndex:deleteIndex];
                                    self.totalComment--; // 总评论数减一
                                    NSLog(@"💎💎💎💎2  删除评论 Comment.count=%ld totalComment=%ld", tempCommentArray.count, self.totalComment);
                                }
                                self.pgcDeteailManager.commentsArray = [tempCommentArray mutableCopy];
                                
                            }
                        } else { // 删除评论下的子评论
                            NSMutableArray *arr = [NSMutableArray arrayWithArray:selectCommentModel.comment.childComment];
                            [arr removeObjectAtIndex:selectChildIndex];
                            selectCommentModel.comment.childComment = arr;
                            NSLog(@"💎💎💎💎3  删除子评论 comment.childComment.count=%ld", arr.count);
                        }
                        
                        [subscriber sendNext:RACTuplePack([self.pgcDeteailManager.hotCommentArray copy], [self.pgcDeteailManager.commentsArray copy])];
                        [subscriber sendCompleted];
                    }
                    
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                }];
                return nil;
            }];
        }];
    }
    return _deleteCommetCommand;
}

/// 评论点赞&取消点赞
- (RACCommand *)commentPariseCommand {
    if (!_commentPariseCommand) {
        @weakify(self);
        _commentPariseCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                SEGSharedCommentModel *commentModel = input;
                SEGSharedCommentInfoModel *infoModel = commentModel.comment;
                SEGSharedCommonUserModel *userModel = commentModel.user;
                
                if (commentModel.comment.isPraise.integerValue == 1) {
                    //这里取消点赞行为方法
                    [self.socialManager requestCancelPraiseByobjId:infoModel.id objType:@"3" Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                        if (isSuccessed) {
                            infoModel.isPraise = @"0";
                            infoModel.praiseCount = [NSString stringWithFormat:@"%d",[infoModel.praiseCount intValue] - 1];
                            [subscriber sendNext:commentModel];
                            [subscriber sendCompleted];
                        }
                        
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                    }];
                } else {
                    //这里执行点赞行为方法
                    [self.socialManager requestPraiseAttentByObjId:infoModel.id
                                                           ObjType:@"3"
                                                   objPicUrlForMsg:nil
                                                    objTitleForMsg:infoModel.content
                                                    byReviewUserId:userModel.userId
                                                       parentObjId:self.pgcID
                                                     parentObjType:self.objType
                                                     operationType:nil
                                                          isParent:nil
                                                          Finished:^(BOOL isSuccessed, NSString *codeType, NSString *errorMessage) {
                        if (isSuccessed) {
                            infoModel.isPraise = @"1";
                            infoModel.praiseCount = [NSString stringWithFormat:@"%d",[commentModel.comment.praiseCount intValue] + 1];
                            [subscriber sendNext:commentModel];
                            [subscriber sendCompleted];
                        }
                        NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                        [subscriber sendError:error];
                    }];
                }
                return nil;
            }];
        }];
    }
    return _commentPariseCommand;
}

/// 是否是加载第一页普通评论数数据
- (BOOL)isLoadFistCommentPage {
    return self.commentPageIndex == 1;
}

#pragma mark - 态度模式处理
/// 态度模式的喜欢和讨厌
- (RACCommand *)postAttributeCommand {
    if (!_postAttributeCommand) {
        @weakify(self);
        _postAttributeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                @strongify(self)
                RACTupleUnpack(SEGSharedCommentModel *commentModel, NSNumber *isAgreeNumber) = input;
                NSString *agreeStatus = isAgreeNumber.boolValue ? @"1" : @"2";
                [self.pgcDeteailManager requestStepOrTopPGCCommentWithPostId:self.pgcID
                                                                   post_type:self.objType
                                                                   commentId:commentModel.comment.id
                                                               commentatorId:commentModel.user.userId
                                                             agreeOrDisagree:agreeStatus
                                                                    finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }];
                return nil;
            }];
        }];
    }
    return _postAttributeCommand;
}

/// 态度模式最后一页请求更多推荐数据
- (RACSignal *)requestRecommendListSignal {
    if (!_requestRecommendListSignal) {
        @weakify(self);
        _requestRecommendListSignal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            @strongify(self);
            [self.pgcDeteailManager requestRecommendPGCWithObjId:self.pgcID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                if (isSuccessed && self.pgcDeteailManager.recommendPGCArray.count > 0) {
                    [subscriber sendNext:self.pgcDeteailManager.recommendPGCArray];
                    [subscriber sendCompleted];
                }
                NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }
    return _requestRecommendListSignal;
}

#pragma mark - 频道列表数据处理
/// 请求主站列表
- (RACCommand *)requestChannelListCommand {
    if (!_requestChannelListCommand) {
        @weakify(self);
        _requestChannelListCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
            @strongify(self);
            return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
                RACTupleUnpack(NSString *channelID, NSNumber *isRefreshNumber) = input;
                BOOL isRefresh = [isRefreshNumber boolValue];
                if (isRefresh) {
                    self.channelPageIndex = 1;
                }
                [self.pgcDeteailManager requestChannelQuery:channelID?:@"" PageNo:self.channelPageIndex PageLimit:10 Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
                    if (isSuccessed) {
                        self.channelPageIndex++;
                        [subscriber sendNext:RACTuplePack(self.pgcDeteailManager.channelmodel, self.pgcDeteailManager.channelDataArrays)];
                        [subscriber sendCompleted];
                    }
                    NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:[codeType integerValue] userInfo:@{NSLocalizedDescriptionKey:errorMessage}];
                    [subscriber sendError:error];
                }];
                return nil;
            }];
        }];
    }
    return _requestChannelListCommand;
}

#pragma mark - Getter
- (SEGPGCDeteailManager *)pgcDeteailManager {
    if (!_pgcDeteailManager) {
        _pgcDeteailManager = [[SEGPGCDeteailManager alloc] init];
    }
    return _pgcDeteailManager;
}

- (SEGCommunitySocialManager *)socialManager {
    if (!_socialManager) {
        _socialManager = [[SEGCommunitySocialManager alloc] init];
    }
    return _socialManager;
}

- (SEGPictorialManager *)pictorialManager {
    if (!_pictorialManager) {
        _pictorialManager = [[SEGPictorialManager alloc] init];
    }
    return _pictorialManager;
}

@end
